#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,tcp(new QTcpSocket(this))
{
    ui->setupUi(this);

    tcp->bind(8888);

    connect(tcp,&QTcpSocket::readyRead,[this](){
        led_append("收到服务器应答：");
        led_append(QString(tcp->readAll()));
    });

    connect(tcp,&QTcpSocket::connected,[this](){
       led_append("连接到默认服务器\n");
    });

    connect(tcp,&QTcpSocket::disconnected,[this](){
        led_append("断开默认服务器的链接\n");
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::led_append(QString str){
    QString info = ui->led->toPlainText();
    info.append(str);
    ui->led->setPlainText(info);
    QTextCursor cursor = ui->led->textCursor();
    cursor.movePosition(QTextCursor::End);  // 移动光标到文档末尾
    ui->led->setTextCursor(cursor);
}

void MainWindow::led_append(const char* str){
    led_append(QString(str));
}

void MainWindow::on_exec_clicked()
{
    led_append("发送请求：");
    led_append(ui->execInput->toPlainText()+"\n");
    tcp->write(ui->execInput->toPlainText().toUtf8());
}

void MainWindow::on_connect_clicked()
{
    tcp->connectToHost("localhost",8000);
}

void MainWindow::on_disconnect_clicked()
{
    tcp->close();
}
